package com.song.codesandbox.backups;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.command.*;
import com.github.dockerjava.api.model.*;
import com.github.dockerjava.core.DockerClientBuilder;
import com.github.dockerjava.core.command.ExecStartResultCallback;
import com.song.codesandbox.CodeSandBox;
import com.song.codesandbox.model.*;
import com.song.codesandbox.utils.ProcessUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StopWatch;

import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Slf4j
public class JavaDockerCodeSandBox implements CodeSandBox {

    /**
     * 全局代码存放目录
     */
    private static final String GLOBAL_CODE_DIR_NAME = "TmpCode";

    /**
     * 全局代码文件名
     */
    private static final String GLOBAL_JAVA_CLASS_NAME = "Main.java";

    /**
     * 超时时间，单位：毫秒
     */
    private static final long TIME_OUT = 5000L;

    /**
     * 镜像初始化状态
     */
    private static boolean FIRST_INIT = true;

    /**
     * 执行代码
     *
     * @param request
     * @return
     */
    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest request) {
        List<String> inputList = request.getInputList();
        String code = request.getCode();
        String language = request.getLanguage();
        if (inputList == null || inputList.isEmpty() || StrUtil.isBlank(code) || StrUtil.isBlank(language)) {
            return createErrorResponse(new IllegalArgumentException("参数不合法"));
        }
        return executeCode(request.getInputList(), request.getCode(), request.getLanguage());
    }

    /**
     * 执行代码
     *
     * @param inputList 程序的输入
     * @param code      程序要执行的代码
     * @param language  编程语言
     * @return
     */
    @Override
    public ExecuteCodeResponse executeCode(List<String> inputList, String code, String language) {

        /**
         * 1. 程序编译与执行的前置准备
         * - 创建用户代码编译与运行的临时目录
         */
        String userDir = System.getProperty("user.dir");
        String globalCodePathName = userDir + File.separator + GLOBAL_CODE_DIR_NAME;
        // 判断全局代码目录是否存在，如果不存在则新建目录
        if (!FileUtil.exist(globalCodePathName)) {
            FileUtil.mkdir(globalCodePathName);
        }

        /**
         * 2. 为用户生成独立的代码存放文件夹，将用户的代码隔离存放
         */
        String userCodeParentPath = globalCodePathName + File.separator + UUID.randomUUID();
        String userCodePath = userCodeParentPath + File.separator + GLOBAL_JAVA_CLASS_NAME;
        File userCodeFile = FileUtil.writeString(code, userCodePath, StandardCharsets.UTF_8);

        /**
         * 3. 编译代码，保存.class文件
         */
        log.info("---------代码编译开始---------");
        String compileCmd = String.format("javac -encoding utf-8 %s", userCodeFile.getAbsoluteFile());
        log.info("编译命令: {}", compileCmd);
        ExecuteMessage compileExecuteMessage = new ExecuteMessage();
        try {
            Process compileProcess = Runtime.getRuntime().exec(compileCmd);
            compileExecuteMessage = ProcessUtils.runProcess(compileProcess, ProcessExecType.COMPILE);
        } catch (IOException e) {
            return createErrorResponse(e);
        }
        log.info("---------代码编译结束---------");

        /**
         * 创建容器，将编译的class文件拷贝到容器中
         */
        // 获取docker客户端
        DockerClient dockerClient = DockerClientBuilder.getInstance().build();
        // 拉取java镜像
        String imageName = "openjdk:8-alpine";
        if (FIRST_INIT) {
            PullImageResultCallback pullImageResultCallback = new PullImageResultCallback() {
                @Override
                public void onNext(PullResponseItem item) {
                    System.out.println("下载镜像: " + item.getStatus());
                    super.onNext(item);
                }
            };
            PullImageCmd pullImageCmd = dockerClient.pullImageCmd(imageName);
            try {
                pullImageCmd.exec(pullImageResultCallback).awaitCompletion();
            } catch (InterruptedException e) {
                System.out.println("拉取镜像异常");
                throw new RuntimeException(e);
            }
            FIRST_INIT = !FIRST_INIT;
        }

        // 创建容器
        CreateContainerCmd containerCmd = dockerClient.createContainerCmd(imageName);
        HostConfig hostConfig = new HostConfig();
        hostConfig.setBinds(new Bind(userCodeParentPath, new Volume("/app")));
        // 设置容器的最大内存
        hostConfig.withMemory(100 * 1000 * 1000L);
        // 限制cpu核数
        hostConfig.withCpuCount(1L);
        hostConfig.withMemorySwap(0L);
        // 配置Docker容器的安全选项
        // hostConfig.withSecurityOpts()
        CreateContainerResponse createContainerResponse = containerCmd
                // 指定文件路径映射, 将本地文件同步到容器中
                .withHostConfig(hostConfig)
                .withAttachStderr(true)
                .withAttachStdin(true)
                .withAttachStdout(true)
                // 禁用网络资源
                .withNetworkDisabled(true)
                // 限制根目录仅读
                .withReadonlyRootfs(true)
                // 交互终端
                .withTty(true)
                .exec();
        System.out.println("容器创建响应: " + createContainerResponse);
        String containerId = createContainerResponse.getId();

        // 启动容器, 执行命令
        dockerClient.startContainerCmd(containerId).exec();

        // 
        ExecCreateCmd execCreateCmd = dockerClient.execCreateCmd(containerId);

        // 循环运行每组输入
        List<ExecuteMessage> executeMessageList = new ArrayList<>();
        for (String inputArgs : inputList) {
            StopWatch stopWatch = new StopWatch();

            // 1. 创建执行命令
            String[] args = inputArgs.split(" ");
            // docker exec interesting_lehmann java -cp /app Main 1 3
            String[] cmdArray = new String[]{"java", "-cp", "app", "Main"};
            cmdArray = ArrayUtil.append(cmdArray, args);
            // 创建一个exec命令
            ExecCreateCmdResponse execCreateCmdResponse = execCreateCmd
                    .withCmd(cmdArray)
                    .withAttachStderr(true)
                    .withAttachStdin(true)
                    .withAttachStdout(true)
                    .exec();
            log.info("创建执行命令: {}", execCreateCmdResponse);

            // 获取exec命令的id
            String execCreateCmdResponseId = execCreateCmdResponse.getId();

            ExecuteMessage executeMessage = new ExecuteMessage();

            final String[] message = {null};
            final String[] errorMessage = {null};
            // 程序是否超时标志
            final boolean[] is_timeout = {true};

            // 命令执行结果回调
            ExecStartResultCallback execStartResultCallback = new ExecStartResultCallback() {
                @Override
                public void onNext(Frame frame) {
                    StreamType type = frame.getStreamType();
                    if (type == StreamType.STDERR) {
                        errorMessage[0] = new String(frame.getPayload());
                        log.info("输出错误结果: {}", new String(frame.getPayload()));
                    } else {
                        message[0] = new String(frame.getPayload());
                        log.info("输出结果: {}", new String(frame.getPayload()));
                    }
                    super.onNext(frame);
                }

                @Override
                public void onComplete() {
                    // 如果程序执行完成，则表示没超时
                    is_timeout[0] = false;
                    super.onComplete();
                }
            };

            /**
             * 启动内存监控程序
             */
            final long[] maxMemory = {0L};
            List<Long> memoryList = new ArrayList<>();
            // 获取占用的内存
            StatsCmd statsCmd = dockerClient.statsCmd(containerId);
            // 构建结果回调函数
            ResultCallback<Statistics> statisticsResultCallback = new ResultCallback<Statistics>() {
                @Override
                public void onStart(Closeable closeable) {

                }

                @Override
                public void onNext(Statistics statistics) {
                    Long memoryUsage = statistics.getMemoryStats().getUsage();
                    maxMemory[0] = Math.max(memoryUsage.longValue(), maxMemory[0]);
                    System.out.println("执行了----");
                    memoryList.add(memoryUsage);
                    log.info("内存监控中, 使用: {}", memoryList);
                }

                @Override
                public void onError(Throwable throwable) {

                }

                @Override
                public void onComplete() {

                }

                @Override
                public void close() throws IOException {

                }
            };
            Closeable closeable = statsCmd.exec(statisticsResultCallback);

            // 执行命令
            long time = 0L;
            try {
                // 开始计时
                stopWatch.start();
                dockerClient
                        // 执行exec命令
                        .execStartCmd(execCreateCmdResponseId)
                        // 回调函数
                        .exec(execStartResultCallback)
                        // 阻塞当前进程，直到回调函数的onComplete方法被调用
                        // 设置超时时间
                        .awaitCompletion();
                // 结束计时
                stopWatch.stop();
                time = stopWatch.getLastTaskTimeMillis();
                statsCmd.close();
            } catch (InterruptedException e) {
                log.info("程序执行异常");
                throw new RuntimeException(e);
            } finally {
                try {
                    closeable.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }

            // todo 此处内存一直为0，仍未找到问题所在
            log.info("使用的最大内存为: {}", maxMemory[0]);
            System.out.println("内存使用:" + memoryList);

            executeMessage.setMessage(message[0]);
            executeMessage.setErrorMessage(errorMessage[0]);
            executeMessage.setTime(time);
            executeMessage.setMemory(maxMemory[0]);
            executeMessageList.add(executeMessage);
        }

        /**
         * 整理输出，构造代码执行的响应结果
         * (1) 输出结果: outputList
         * (2) 接口信息: message
         * (3) 执行状态: status
         *      1: 执行成功
         *      2: 异常
         *      3: 执行失败
         * (5) 判题信息: judgeInfo
         *    判题信息包括：程序执行信息(message)、消耗时间(time)以及消耗内存(memory)
         */
        ExecuteCodeResponse response = new ExecuteCodeResponse();
        List<String> outputList = new ArrayList<>();
        long maxTime = 0L;
        // 遍历所有执行信息
        for (ExecuteMessage executeMessage : executeMessageList) {
            String errorMessage = executeMessage.getErrorMessage();
            if (StrUtil.isNotBlank(errorMessage)) {
                response.setMessage(errorMessage);
                response.setStatus(3);
                break;
            }
            outputList.add(executeMessage.getMessage());
            if (executeMessage.getTime() != null) {
                maxTime = Math.max(maxTime, executeMessage.getTime());
            }
        }

        if (outputList.size() == executeMessageList.size()) {
            response.setStatus(1);
        }
        response.setOutputList(outputList);
        JudgeInfo judgeInfo = new JudgeInfo();
        judgeInfo.setTime(maxTime);
        response.setJudgeInfo(judgeInfo);

        return response;
    }

    /**
     * 构建异常错误响应
     *
     * @param e 异常状态
     * @return 异常错误响应
     */
    private ExecuteCodeResponse createErrorResponse(Throwable e) {
        ExecuteCodeResponse response = new ExecuteCodeResponse();
        response.setOutputList(new ArrayList<>());
        response.setMessage(e.getMessage());
        response.setStatus(2);
        response.setJudgeInfo(new JudgeInfo());
        return response;
    }


    /**
     * 执行代码示例
     *
     * @param args
     */
    public static void main(String[] args) {
        JavaDockerCodeSandBox javaDockerCodeSandBox = new JavaDockerCodeSandBox();

        String code = ResourceUtil.readStr("test/computeArgs/Main.java", StandardCharsets.UTF_8);
//        String code = ResourceUtil.readStr("test/unSafeCode/ReadFileError.java", StandardCharsets.UTF_8);
        ExecuteCodeRequest request = ExecuteCodeRequest.builder().inputList(Arrays.asList("1 2", "3 4")).code(code).language("java").build();

        ExecuteCodeResponse response = javaDockerCodeSandBox.executeCode(request);
    }
}
